{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from datetime import datetime\n",
    "\n",
    "from datetime import datetime\n",
    "import fxcmpy\n",
    "from sklearn import svm\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "TOKEN =''\n",
    "con = fxcmpy.fxcmpy(access_token=TOKEN, log_level='error')\n",
    "\n",
    "con.is_connected()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fxcmpy.__version__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "to_show = ['tradeId', 'amountK','currency','grossPL','isBuy']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lags = 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = svm.SVC(C=100, probability=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_features(df, lags):\n",
    "    df['Returns'] = np.log(df['Mid'] /df['Mid'].shift(1))\n",
    "    print(df)\n",
    "    cols = []\n",
    "    for lag in range(1, lags +1):\n",
    "        col = 'lag_%s' % lag\n",
    "        print(\"col = \", col)\n",
    "        df[col] = np.sign(df['Returns'].shift(lag))\n",
    "        cols.append(col)\n",
    "    df.dropna(inplace=True)\n",
    "    return df, cols"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "candles = con.get_candles('EUR/USD', period='m1', number=1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.DataFrame(candles[['askclose', 'bidclose']].mean(axis=1),\n",
    "                   columns=['Mid'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data, cols = generate_features(data, lags)\n",
    "data.tail()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.fit(data[cols], np.sign(data['Returns']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ticks=0\n",
    "position=0\n",
    "tick_data=pd.DataFrame()\n",
    "tick_resam=pd.DataFrame()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def automated_trading(data,df):\n",
    "    global lags,model,ticks\n",
    "    global tick_data,tick_resan,to_show\n",
    "    global position\n",
    "    ticks += 1\n",
    "    t =datetime.now()\n",
    "    if ticks % 5==0 :\n",
    "        print('%3d|%s| %7.5f | %7.5f' % (ticks, str(t.time()),\n",
    "                                         data['Rates'][0],data['Rates'][1]))\n",
    "    \n",
    "    #collecting tick data    \n",
    "    tick_data=tick_data.append(pd.DataFrame(\n",
    "        {'Bid':data['Rates'][0],'Ask':data['Rates'][1],\n",
    "         'High':data['Rates'][2],'Low':data['Rates'][3]},\n",
    "         index=[t]))  \n",
    "    \n",
    "    #resampling tick data\n",
    "    tick_resam=tick_data[['Bid','Ask']].resample('5s',label='right').last().ffill()\n",
    "    tick_resam['Mid'] = tick_resam.mean(axis=1)\n",
    "    time.sleep(1)\n",
    "    if len(tick_resam) > lags + 2:\n",
    "        #generate a signal\n",
    "        tick_resam, cols = generate_features(tick_resam, lags)\n",
    "        tick_resam['Prediction'] = model.predict(tick_resam[cols])\n",
    "        #entering a long position \n",
    "        if tick_resam['Prediction'].iloc[-2] >= 0 and position == 0:\n",
    "            print('going long (for the first time)')\n",
    "            position = 1\n",
    "            order = con.create_market_buy_order('EUR/USD', 25)\n",
    "            trade = True \n",
    "        elif tick_resam['Prediction'].iloc[-2] >= 0 and position == -1:\n",
    "            print('going long')\n",
    "            position = 1\n",
    "            order = con.create_market_buy_order('EUR/USD', 50)\n",
    "            trade = True\n",
    "        #entering a short positon \n",
    "        elif tick_resam['Prediction'].iloc[-2] <= 0 and position == 0:\n",
    "            print('going short (for the first time)')\n",
    "            position = -1\n",
    "            order = con.create_market_buy_order('EUR/USD', 25)\n",
    "            trade = True\n",
    "        elif tick_resam['Prediction'].iloc[-2] <= 0 and position == 1:\n",
    "            print('going short')\n",
    "            position = -1\n",
    "            order = con.create_market_buy_order('EUR/USD', 50)\n",
    "            trade = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "con.subscribe_market_data('EUR/USD', (automated_trading,))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
